from django.core.paginator import Paginator
from django.db import IntegrityError
from django.db.models import ProtectedError
from django.shortcuts import render, redirect, reverse

from app08.models import Dept, User, UserForm, Employee, EmployeeForm
import hashlib
from app08.utils.customer_utile import page_util


# Create your views here.

def dept_list(request):
    if request.method == 'GET':
        dept_list = Dept.objects.all().values().order_by('-id')
        return render(request, 'dept/dept_list.html', {'dept_list': dept_list})


def dept_add(request):
    if request.method == 'GET':
        return render(request, 'dept/dept_add.html')

    # 获取数据添加
    name = request.POST.get('name')
    address = request.POST.get('address')
    dept = Dept(name=name, address=address)

    # 可能出现异常信息    部门名称不能重复
    try:
        dept.save()
    except IntegrityError as e:
        # 字段重复
        return render(request, 'dept/dept_add.html', {'error': '部门名称重复'})

    # 根据路由名字 解析路径
    path = reverse('dept_list')
    print(path)
    # 重定向    /app08/dept/list  耦合
    return redirect(path)


def dept_edit(request, id):
    if request.method == 'GET':
        dept = Dept.objects.filter(id=id).values().first()
        return render(request, 'dept/dept_edit.html', {'dept': dept})

    # 编辑数据
    name = request.POST.get('name')
    address = request.POST.get('address')

    try:
        Dept.objects.filter(id=id).update(name=name, address=address)
    except IntegrityError as e:
        # 字段重复
        context = {
            'error': '部门名称重复',
            'dept': {
                'id': id,
                'name': name,
                'address': address
            }
        }
        return render(request, 'dept/dept_edit.html', context=context)
    path = reverse('dept_list')
    return redirect(path)


# 删除部门信息
def dept_delete(request, id):
    # 删除部门信息

    try:
        Dept.objects.filter(id=id).delete()
    except ProtectedError as e:
        #  会话对象  session
        request.session['error'] = '有外键关联不能删除该数据!!!'
        # 2秒
        request.session.set_expiry(2)
    path = reverse('dept_list')
    return redirect(path)


def user_list(request):
    if request.method == 'GET':
        users = User.objects.all().order_by('-id')
        for user in users:
            print(user.get_gender_display())
        return render(request, 'user/user_list.html', context={'users': users})


def user_add(request):
    if request.method == 'GET':
        # 创建userForm表单对象
        form = UserForm()
        return render(request, 'user/user_add.html', context={'form': form})
    # 获取数据
    user_form = UserForm(data=request.POST)
    # 动态添加属性值  默认密码 111111
    user_form.instance.password = hashlib.md5('111111'.encode('utf-8')).hexdigest()
    # 数据校验功能
    if user_form.is_valid():
        # 保存数据
        user_form.save()
        return redirect(reverse('user_list'))
    # 校验失败
    return render(request, 'user/user_add.html', context={'form': user_form})


def user_edit(request, id):
    user = User.objects.filter(id=id).first()
    if request.method == 'GET':
        form = UserForm(instance=user)
        return render(request, 'user/user_edit.html', context={'form': form})

    # 修改数据   instance  修改前的数据   id    data=request.POST   最新表单数据值
    user_form = UserForm(data=request.POST, instance=user)
    # 执行更新
    if user_form.is_valid():
        user_form.save()
        return redirect(reverse('user_list'))
    return render(request, 'user/user_edit.html', context={'form': user_form})


def user_delete(request, id):
    User.objects.filter(id=id).delete()
    path = reverse('user_list')
    return redirect(path)


def user_login(request):
    if request.method == 'GET':
        return render(request, 'login/login.html')

    username = request.POST.get('username')
    password = request.POST.get('password')
    # 数据库中的密码是经过摘要算法的结果
    password = hashlib.md5(password.encode('utf-8')).hexdigest()
    user = User.objects.filter(username=username, password=password).first()
    if user is None:
        return render(request, 'login/login.html', context={'error': '用户名或密码错误'})

    # 用户认证通过   保存用户信息  username  id  is_auth   session
    request.session['username'] = user.username
    request.session['uid'] = user.id
    request.session['is_auth'] = True

    return redirect(reverse('user_list'))


# 退出登录
def user_logout(request):
    # 清空session  销毁session
    request.session.flush()
    return redirect(reverse('user_login'))


# 个人信息修改
def user_personal(request):
    if request.method == 'GET':
        user = User.objects.filter(id=request.session['uid']).first()
        return render(request, 'user/user_personal.html', {'user': user})

    age = request.POST.get('age')
    gender = request.POST.get('gender')
    User.objects.filter(id=request.session['uid']).update(age=age, gender=gender)
    return redirect(reverse('user_list'))


# 个人密码修改
def user_personal_pwd(request):
    if request.method == 'GET':
        return render(request, 'user/user_personal_pwd.html')

    # 获取密码
    old_pwd = hashlib.md5(request.POST.get('old_pwd').encode('utf-8')).hexdigest()
    new_pwd = request.POST.get('new_pwd')
    # 根据id 查询用户信息
    user = User.objects.filter(id=request.session['uid']).first()
    db_pwd = user.password
    if old_pwd != db_pwd:
        return render(request, 'user/user_personal_pwd.html', {'error': '原始密码不正确'})

    # 修改密码
    User.objects.filter(id=request.session['uid']).update(password=hashlib.md5(new_pwd.encode('utf-8')).hexdigest())
    return redirect(reverse('user_logout'))


# 列表渲染
def emp_list(request):
    if request.method == 'GET':
        emp_list = Employee.objects.all().order_by('-id')
        return render(request, 'emp/emp_list.html', {'emp_list': emp_list})


# 分页查询
"""
  前端 -> 后端
  1. 当前页  current_page
  2. 每页展示的条数  size
  
  后端 -> 前端
  1. 当前页数据
  2. 总条数
  3. 总页数
  4. 分页区间
"""


def emp_page(request):
    # 查询所有数据
    emp_list = Employee.objects.all().order_by('-id')
    context = page_util(request, emp_list)
    return render(request, 'emp/emp_list.html', context=context)


def emp_add(request):
    if request.method == 'GET':
        form = EmployeeForm()
        return render(request, 'emp/emp_add.html', {'form': form})
    # 保存员工信息
    form = EmployeeForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect(reverse('emp_page'))

    return render(request, 'emp/emp_add.html', context={'form': form})


def emp_edit(request, id):
    emp = Employee.objects.filter(id=id).first()
    if request.method == 'GET':
        emp_form = EmployeeForm(instance=emp)
        return render(request, 'emp/emp_edit.html', {'form': emp_form})

    # 修改数据
    form = EmployeeForm(instance=emp, data=request.POST)
    if form.is_valid():
        form.save()
        return redirect(reverse('emp_page'))
    return render(request, 'emp/emp_edit.html', context={'form': form})


def emp_delete(request, id):
    Employee.objects.filter(id=id).delete()
    path = reverse('emp_page')
    return redirect(path)
